package com.oazon.moco.link.core;

import android.util.Log;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

import com.oazon.moco.link.core.source.LanEventSource;
import com.oazon.moco.link.core.source.LinkEventSource;
import com.oazon.moco.link.core.source.SerialEventSource;
import com.oazon.moco.link.core.source.SpeakEventSource;
import com.oazon.moco.link.core.source.SystemEventSource;
import com.oazon.moco.link.core.source.UIEventSouce;

/**
 * @author chengke
 *
 */
public class LinkEventController implements ILinkEventController{

	private Collection<LinkEventListener> listeners;
	public static LinkEventSource lanSource = new LanEventSource();
	public static LinkEventSource serialSource = new SerialEventSource();
	public static LinkEventSource uiSource = new UIEventSouce();
	public static LinkEventSource speakEventSource = new SpeakEventSource();
	public static LinkEventSource systemEventSource = new SystemEventSource();
	
	private static LinkEventController instance = new LinkEventController();
	
	public static LinkEventController getInstance(){
		return instance;
	}
	
	/**
     * 添加事件，默认是每个对象只添加一次
     * 
     * @param listener
     *            DoorListener
     */
	@Override
    public synchronized void registLinkListener(LinkEventListener listener) {
		registLinkListener(listener,true);
    }
	
	
    /**
     * 添加事件
     * 
     * @param listener
     *            DoorListener
     * @param singleton
     * 			singleton表示当前listener是否可以被重复添加           
     */
	@Override
    public synchronized void registLinkListener(LinkEventListener listener ,boolean singleton) {
		boolean isExist = false;
        if (listeners == null) {
            listeners = new HashSet<LinkEventListener>();
        }
	    for (LinkEventListener linkEventListener : listeners) {
			if(linkEventListener == listener){
				isExist = true;
			}
		}
	    if(isExist && singleton){
	       return;
	    }
	    listeners.add(listener);
    }

    /**
     * 移除事件
     * 
     * @param listener
     *            DoorListener
     */
	@Override
    public synchronized void unregistLinkListener(LinkEventListener listener) {
        if (listeners == null)
            return;
        listeners.remove(listener);
    }
    
    /**
     * 通知所有的DoorListener
     */
	@Override
    public synchronized void notifyListeners(LinkEvent event) {
        Iterator<LinkEventListener> iter = listeners.iterator();
        while (iter.hasNext()) {
        	LinkEventListener listener = iter.next();
            listener.onLinkEvent(event);
            
        }
    }
	
	@Override
	public void notify(String uuid, LinkEvent Event) {
		// TODO Auto-generated method stub
		throw new RuntimeException("not support this methord now!");
	}

	@Override
	public void notify(LinkEventSource source,LinkEvent event) {
		// TODO Auto-generated method stub
		throw new RuntimeException("not support this methord now!");
	}
}
